#include "IPCAM_Export.h"
#include "Daemon.h"
#include "Daemon_FacInfoCtl.h"
#include "Daemon_GetNetInfo.h"
#include "Daemon_DevFoundBrost.h"
#include "Daemon_Common.h"
//#include <sys/reboot.h>
#include "Daemon_UpgradeByNet.h"
#include "Daemon_DevFound.h"
#include "Daemon_Init.h"
#ifdef FACTOOL_PROTOCOL
#include "FacTool.h"
#endif

static void* Func_age(void* args)
{
	int iRet = 0;
	IPCAM_DEBUG("#############Func_age//Func_age################");
	while(1){
		iRet ++;
		iRet --;

		iRet ++;
		iRet --;

		iRet ++;
		iRet --;
	}
	return NULL;
}

static INT GetDevSysInfo(ULONG *runTime, ULONG *freeMem)
{
#ifdef __HuaweiLite__
    UINT32 uwMemUsed = 0;
    UINT32 uwTotalMem = 0;
    UINT32 uwFreeMem = 0;

    uwMemUsed = LOS_MemTotalUsedGet(m_aucSysMem1);
    uwTotalMem = LOS_MemPoolSizeGet(m_aucSysMem1);
    uwFreeMem = uwTotalMem - uwMemUsed;

    if (runTime != NULL) {
        *runTime = 0;
    }
    if (freeMem != NULL) {
        *freeMem = uwFreeMem;
    }    
#else
    struct sysinfo info;
    memset(&info, 0, sizeof(info));
    sysinfo(&info);
    if (runTime != NULL) {
        *runTime = info.uptime;
    }
    if (freeMem != NULL) {
        *freeMem = info.freeram;
    }
#endif /* __HuaweiLite__ */

    return 0;
}

static INT GetDevSelfCode(ULONG *AppSelfCode)
{
    ULONG freeMem = 0;
	INT 			code[2];
	struct timeval	tival	= {0};
	gettimeofday(&tival, NULL);

	code[0] = (INT )tival.tv_usec % 10000000;
	GetDevSysInfo(NULL, &freeMem);
	code[1] = (INT )freeMem % 100000;
	*AppSelfCode = code[0] + code[1];
	return TRUE;
}

static INT CreateSendSocketFd(INT *pSendSocketFd, struct sockaddr_in *pSendAddr)
{
	//INT 			SendSocketFd	= -1;
	//INT 			enable			=  1;

	if (0 >= (*pSendSocketFd = socket(AF_INET, SOCK_DGRAM, 0))){
		perror("Socket ERr");
		return FALSE;
	} 
	const int opt = 1;	
	//设置该套接字为广播类型，	
	int nb = 0;  
	nb = setsockopt(*pSendSocketFd, SOL_SOCKET, SO_BROADCAST, (char *)&opt, sizeof(opt));  
	if(nb == -1)  
	{  
		LOGE("set socket error...\n");  
		return FALSE;  
	}
	bzero(pSendAddr, sizeof(struct sockaddr_in));  
	pSendAddr->sin_family=AF_INET;	
	pSendAddr->sin_addr.s_addr=htonl(INADDR_BROADCAST);  
	pSendAddr->sin_port=htons(PORT_DEVFIND_BROADCAST_UDP_RESP);  
   
	return TRUE;
}

static INT CreateRecvSocketFd(INT *pRecvSocketFd, struct sockaddr_in *pRecvAddr, in_addr_t in_addr)
{
	INT 				enable	= 1;
	INT 				socklen;
	//struct ip_mreq		mreq;
	
	if (0 >= (*pRecvSocketFd = socket(AF_INET, SOCK_DGRAM, 0))){
		return FALSE;
	}

 
	const int opt = 1;	
	//设置该套接字为广播类型，	
	int nb = 0;  

	nb = setsockopt(*pRecvSocketFd, SOL_SOCKET, SO_BROADCAST, (char *)&opt, sizeof(opt));  
	if(nb == -1)  
	{  
		LOGE("set socket error...\n");  
		return FALSE;  
	}
	setsockopt(*pRecvSocketFd, SOL_SOCKET, SO_REUSEADDR, (CHAR *)&enable, sizeof(ULONG INT));
	socklen = sizeof(struct sockaddr_in);
	memset(pRecvAddr, 0, socklen);
	pRecvAddr->sin_family	= AF_INET;
	pRecvAddr->sin_port 	= htons(PORT_DEVFIND_BROADCAST_SEARCH);
	if (bind(*pRecvSocketFd, (struct sockaddr *)pRecvAddr,sizeof(struct sockaddr_in)) == -1) {
		perror("Bind error");
		close(*pRecvSocketFd);
		return FALSE;
	}

	return TRUE;
}

static INT CheckGetWay(UCHAR* IpAddr,UCHAR* NetMask,UCHAR* NetGetWay)
{
   
	INT i;
	struct in_addr ip;
	struct in_addr mask;	
	struct in_addr gw;
	ip.s_addr=inet_addr((char*)IpAddr);
	mask.s_addr=inet_addr((char*)NetMask);
	gw.s_addr=inet_addr((char*)NetGetWay);

	CHAR ip_addr[4],net_mask[4],net_gw[4];
	memcpy(ip_addr,&ip.s_addr,4);
	memcpy(net_mask,&mask.s_addr,4);
	memcpy(net_gw,&gw.s_addr,4);

	IPCAM_DEBUG("Debug CheckGetWay.........");

	for(i=0;i<4;i++){
        ip_addr[i] = ip_addr[i]&net_mask[i];
		net_gw[i]  = net_gw[i]&net_mask[i];
	}
	if(!strcasecmp((char*)ip_addr,net_gw)){
		IPCAM_DEBUG("Net Rule Modify Enable");
		return 0;
	}else{
		IPCAM_DEBUG("Net Rule Modify Unable");
		return -1;
	}
}

static int popen_cmd(char *cmd, char *type, char *ret, int retSize)
{
	FILE *fp = NULL;
	if (NULL == (fp = popen(cmd, type))){
		IPCAM_DEBUG("popen %s error", cmd);
		return -1;
	}
	memset(ret, 0, retSize);
	fread(ret, retSize-1, 1, fp);

	pclose(fp);
	return 0;
}

static int get_wifi_gateway(const char *ifrname, char *gateway)
{
	char buf[8192];
	char *p = buf;
	char dev[10];
	popen_cmd("ip route show", "r", buf, sizeof(buf));
	while(NULL != (p = strstr(p, "default via"))){
		sscanf(p, "default via %s dev %s", gateway, dev);
		if(0 == strcasecmp(dev, ifrname)){
			return 0;
		}
		p += strlen("default via");
	}
	gateway[0] = '\0';
	return -1;
}

static int get_hardware_version(char *HVersion, int len)
{
	if(HVersion == NULL)
		return -1;
	
	memset(HVersion, 0, len);

#if 0
    sprintf(HVersion,"%s",ProductGetHandle()->HardWareVersion); 
#else
    DevConfigGetHardVersion(HVersion, len);
#endif

	return 0;
}

static int get_software_version(char *SVersion, int len)
{
#ifdef __HuaweiLite__
    if (SVersion != NULL) {
        DevGetSoftVersion(SVersion);
    }

    int ret = 0;
    static char mcuVer[32] = "";
    if (strlen(mcuVer) == 0) {
        char verBuf[32] = "";
        DevConfigGetMcuVersion(verBuf, sizeof(verBuf));
        char *p = NULL;
        p = strstr(verBuf, "V");
        if (p != NULL) {
            snprintf(mcuVer, sizeof(mcuVer), "%s", p);
            p = NULL;
        }        
    }  
    if (strlen(mcuVer) != 0) {

        char socSubName[16] = ""; 
        if (PRODUCT_MODEL_B1 == ProductGetHandle()->ProductModel) {
            snprintf(socSubName, sizeof(socSubName), "%s", "MCU");
        } else {
            snprintf(socSubName, sizeof(socSubName), "%s", "WIFI");
        }
        
        #ifdef MINI_APP
        snprintf(SVersion, len, "%s_%s%s_BAK", SVersion, socSubName,  mcuVer);
        #else
        snprintf(SVersion, len, "%s_%s%s", SVersion, socSubName, mcuVer);
        #endif /* MINI_APP */
    }
#else
	FILE *fp = NULL;
	int    i = 0;
	
	if(SVersion == NULL)
		return -1;
	
	memset(SVersion, 0, len);
	
	if(NULL == (fp = fopen(SOFTVER_FILE_PATH, "r"))){
		return -1;
	}
	
	if(0 >= (i = fread(SVersion, 1, len, fp))){
		fclose(fp);
		fp = NULL;
		return -1;
	}
	
	if(SVersion[i - 1] == '\n')
		SVersion[i - 1] = '\0';
    
	fclose(fp);
	fp = NULL;
#endif /* __HuaweiLite__ */

	return 0;
}
static int net_detect(char* net_name)
{
    int skfd = 0;
    struct ifreq ifr;

    skfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(skfd < 0) 
	{
		LOGE("%s:%d Open socket error!\n", __FILE__, __LINE__);
		return FALSE;
    }

    strcpy(ifr.ifr_name, net_name);

    if(ioctl(skfd, SIOCGIFFLAGS, &ifr) <0 )
	{
		LOGD("%s:%d IOCTL error!", __FILE__, __LINE__);
		LOGD("Maybe ethernet inferface %s is not valid!", ifr.ifr_name);
		close(skfd);
		return FALSE;
    }
	close(skfd);
    if(ifr.ifr_flags & IFF_RUNNING) 
	{
        return TRUE;
    } 

    return FALSE;
}


static VOID *Pthread_NetDevBroadCastFound1(VOID *args)
{
	struct sockaddr_in s_addr;
	struct sockaddr_in c_addr;
	int sock;
	socklen_t addr_len;
	int len;
	char buff[128];
	int yes = 1;
	if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) 
	{
		perror("socket");
		exit(EXIT_FAILURE);
	} else
		printf("create socket.\n\r");
	memset(&s_addr, 0, sizeof(struct sockaddr_in));

    setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &yes, sizeof(yes));
    
	s_addr.sin_family = AF_INET;							
	s_addr.sin_port = htons(7838);	
	s_addr.sin_addr.s_addr = INADDR_ANY;
	if ((bind(sock, (struct sockaddr *) &s_addr, sizeof(s_addr))) == -1) 
	{
		perror("bind");
		exit(EXIT_FAILURE);
	} else
		printf("bind address to socket.\n\r");
	addr_len = sizeof(c_addr);


    struct timeval      TimeOut;
    fd_set              FdSet;
    INT                 iRet                = -1;

	while (1) 
	{
        TimeOut.tv_sec  = 10;
        TimeOut.tv_usec = 1000;
        FD_ZERO(&FdSet);
        FD_SET(sock , &FdSet);    
        if(0 >= (iRet = select(sock + 1, &FdSet, 0, 0, &TimeOut)))
        {
            continue;
        }

		len = recvfrom(sock, buff, sizeof(buff) - 1, 0,	
				(struct sockaddr *) &c_addr, &addr_len);
		if (len < 0) 
		{
			perror("recvfrom");
			exit(EXIT_FAILURE);
		}
		buff[len] = '\0';
		printf("recive come from %s:%d message:%s\n\r",
			inet_ntoa(c_addr.sin_addr), ntohs(c_addr.sin_port), buff);
	}

    pthread_exit(0);
}

static VOID *Pthread_NetDevBroadCastFound(VOID *args)
{
	INT 				SendSocketFd		= -1;
	INT 				RecvSocketFd		= -1;
	socklen_t			AddrLen				= sizeof(struct sockaddr_in);
	struct sockaddr_in 	SendAddr			= {0};
	struct sockaddr_in 	RecvAddr			= {0};
	struct sockaddr_in 	eth0Addr			= {0};
	struct sockaddr_in 	ra0Addr				= {0};
	CHAR				eth0IpAddr[16]		= {0};
	CHAR				ra0IpAddr[16]		= {0};
	CHAR				tmpEth0IpAddr[16]	= {0};
	CHAR				tmpRa0IpAddr[16]	= {0};
	INT 				Ra0SendSocketFd		= -1;
    INT                 MaxRecvSocketFd     = -1; 
	INT					iRet				= -1;
	ULONG				DevSelfCode			= 0;
	CHAR			   *pMacAddr			= calloc(sizeof(CHAR), 24);
	CHAR 		   		Cmd[128] 			= {0};
	CHAR				HVersion[32]		= {0};
	CHAR				SVersion[32]		= {0};
	//LPTHREAD_ARG 		*parg   			= (LPTHREAD_ARG *)args;
	NETMSGPACKET		NetPacket;
	DM_SYSNETINFO		NetInfo;
	SAVENANDINFO_T  	FacInfo;
	struct timeval		TimeOut;
	fd_set				FdSet;
	struct tm *t;
	time_t timetmp;
	time_t LastTime = {0};
	time_t CurrTime = {0};
	
	memset(&NetPacket, 0, sizeof(NETMSGPACKET));
	memset(&NetInfo, 0, sizeof(DM_SYSNETINFO));
	memset(&FacInfo, 0, sizeof(SAVENANDINFO_T));

	pthread_detach(pthread_self());
	GetDevSelfCode(&DevSelfCode);
	get_hardware_version(HVersion, sizeof(HVersion));
	get_software_version(SVersion, sizeof(SVersion));

	while( TRUE )
	{	
		if(RecvSocketFd <= 0 && FALSE == CreateRecvSocketFd(&RecvSocketFd, &RecvAddr, htonl(INADDR_ANY)))
		{
			sleep(1);
			continue;
		}
			
   		memset(tmpEth0IpAddr, 0, sizeof(tmpEth0IpAddr));
		pox_get_ipaddr(NET_ETH, tmpEth0IpAddr);
	#if 0
		if(net_detect(NET_ETH) && 0 != tmpEth0IpAddr[0] &&
			(SendSocketFd < 0 || 0 != strcmp(eth0IpAddr, tmpEth0IpAddr)) )
		{
			if(SendSocketFd > 0)	close(SendSocketFd);
			
			strcpy(eth0IpAddr, tmpEth0IpAddr);

			if(TRUE == CreateSendSocketFd(&SendSocketFd, &SendAddr))
			{	
				eth0Addr.sin_family 	= AF_INET;
				eth0Addr.sin_port 		= htons(PORT_DEVFIND_BROADCAST_UDP_RESP);
				inet_pton(AF_INET, eth0IpAddr, &(eth0Addr.sin_addr));
				bind(SendSocketFd, (struct sockaddr *)&eth0Addr, sizeof(struct sockaddr));
			}
			
            if(RecvSocketFd > 0) close(RecvSocketFd);
            RecvSocketFd = -1;
            continue;
		}
	#endif

   		memset(tmpRa0IpAddr, 0, sizeof(tmpRa0IpAddr));
		pox_get_ipaddr(NET_WLAN, tmpRa0IpAddr);	
		if(net_detect(NET_WLAN) && 0 != tmpRa0IpAddr[0] && 
			(Ra0SendSocketFd <0 || 0 != strcmp(ra0IpAddr, tmpRa0IpAddr)))
		{
			if(Ra0SendSocketFd > 0)	close(Ra0SendSocketFd);

			strcpy(ra0IpAddr, tmpRa0IpAddr);

			if(TRUE == CreateSendSocketFd(&Ra0SendSocketFd, &SendAddr))
			{
				ra0Addr.sin_family	 	= AF_INET;
				ra0Addr.sin_port 		= htons(PORT_DEVFIND_BROADCAST_UDP_RESP);
				inet_pton(AF_INET, ra0IpAddr, &(ra0Addr.sin_addr));
				bind(Ra0SendSocketFd, (struct sockaddr *)&ra0Addr, sizeof(struct sockaddr));
			}
			
            if(RecvSocketFd > 0) close(RecvSocketFd);
            RecvSocketFd = -1;
            continue;
		}
		
		TimeOut.tv_sec  = 10;
		TimeOut.tv_usec = 1000;
		FD_ZERO(&FdSet);
		FD_SET(RecvSocketFd , &FdSet);
		MaxRecvSocketFd = RecvSocketFd + 1;;
        
		if(0 >= (iRet = select(MaxRecvSocketFd, &FdSet, 0, 0, &TimeOut)) && Upgrade_now == 0)
		{
			if(0 == iRet)
			{
			//	memset(Cmd,0,sizeof(Cmd));
			//	if(SendSocketFd > 0)
			//		sendto(SendSocketFd, Cmd, 32, 32,(struct sockaddr*) &SendAddr, AddrLen);
			//	if(Ra0SendSocketFd > 0)
			//		sendto(Ra0SendSocketFd, Cmd, 32, 32,(struct sockaddr*) &SendAddr, AddrLen);
			}

			if(RecvSocketFd > 0)	close(RecvSocketFd);
			RecvSocketFd	= -1;

			continue;
		}
   		memset(&NetPacket, 0, sizeof(NetPacket));
		iRet = recvfrom(RecvSocketFd, (NETMSGPACKET *)&NetPacket, sizeof(NETMSGPACKET), 0, (struct sockaddr  *)&RecvAddr, &AddrLen);

		if( iRet != sizeof(NETMSGPACKET) || iRet <= 0 || NetPacket.MsgHead.sync != __start_code__ )
		{
			if(Upgrade_now == 0)
			{
				if(LastTime == 0)	time(&LastTime);
				else				time(&CurrTime);

				if(CurrTime >= LastTime + 10) 
				{
					memset(Cmd,0,sizeof(Cmd));
#ifdef __HuaweiLite__
					if(SendSocketFd > 0)
						sendto(SendSocketFd, Cmd, 32, 0,(struct sockaddr*) &SendAddr, AddrLen);
					if(Ra0SendSocketFd > 0)
				        sendto(Ra0SendSocketFd, Cmd, 32, 0,(struct sockaddr*) &SendAddr, AddrLen);
#else
					if(SendSocketFd > 0)
						sendto(SendSocketFd, Cmd, 32, 32,(struct sockaddr*) &SendAddr, AddrLen);
					if(Ra0SendSocketFd > 0)
				        sendto(Ra0SendSocketFd, Cmd, 32, 32,(struct sockaddr*) &SendAddr, AddrLen);
#endif /* __HuaweiLite__ */						
					LastTime = CurrTime;
				}				
			}

			
			usleep(500*1000);
			continue;
		}
		else
		{
			LastTime = 0;
		} 
		
		IPCAM_DEBUG("DevSelfCode = %lu, subType = %u", DevSelfCode, NetPacket.MsgHead.subType);
		if( NetPacket.MsgHead.msgType == MSG_SEARCHQUERY_REQ )
		{
#ifdef SYSTEM_SAFE_MODE            
            static char bUpgradeNetStarted = 0;
            if (!bUpgradeNetStarted) {
                bUpgradeNetStarted = 1;
                THREAD_ARG Sarg_Net;
                Daemon_StartUpGradeByNet(&Sarg_Net); //通过网络启动的更新
                FacTool_Init();
            }
#endif /* SYSTEM_SAFE_MODE */
			IPCAM_DEBUG("------Search Dev----------");
			//查看包类型，按类型操作: 设备搜索;
			memset(&NetInfo, 0, sizeof(NetInfo));
			if (FALSE == Daemon_GetNetInfo(&NetInfo))
			{
				IPCAM_DEBUG("Get NetInfo Fail");
			}
			IPCAM_DEBUG("IP %s gw %s mask %s mac %s", NetInfo.NetIpAddr, NetInfo.NetGwAddr, 
				NetInfo.NetSubMask, NetInfo.NetMacAddr);
			memset(&FacInfo, 0, sizeof(FacInfo));
			IPCAM_ReadFacInfo((VOID*)&FacInfo);
			IPCAM_DEBUG("T_DEVSEARCHINFO = %d",sizeof(NetPacket.MsgDevSearch.DevSearchInfo));
			NetPacket.MsgDevSearch.DevSearchInfo.iServerPort 	= 		60001;		
			strcpy((char*)NetPacket.MsgDevSearch.DevSearchInfo.NetIpAddr,	(char*)NetInfo.NetIpAddr);
			strcpy((char*)NetPacket.MsgDevSearch.DevSearchInfo.NetGwAddr,	(char*)NetInfo.NetGwAddr);
			strcpy((char*)NetPacket.MsgDevSearch.DevSearchInfo.NetSubMask, 	(char*)NetInfo.NetSubMask);
			strcpy((char*)NetPacket.MsgDevSearch.DevSearchInfo.NetMacAddr, 	(char*)NetInfo.NetMacAddr);
			strcpy((char*)NetPacket.MsgDevSearch.DevSearchInfo.NetDnsSvI,	(char*)NetInfo.NetDnsSvI);
			strcpy((char*)NetPacket.MsgDevSearch.DevSearchInfo.NetDnsSvII, 	(char*)NetInfo.NetDnsSvII);
			strcpy((char*)NetPacket.MsgDevSearch.DevSearchInfo.devModel,	(char*)FacInfo.devModel);
			strcpy((char*)NetPacket.MsgDevSearch.DevSearchInfo.devSerialNumb,(char*)FacInfo.devSerialNumb);
			strcpy((char*)NetPacket.MsgDevSearch.DevSearchInfo.devRegcode, 	(char*)FacInfo.devRegcode);
			strcpy((char*)NetPacket.MsgDevSearch.DevSearchInfo.devName, 	(char*)FacInfo.devName);
			strcpy((char*)NetPacket.MsgDevSearch.DevSearchInfo.szFactoryName,(char*)FacInfo.szFactoryName);
   			strcpy((char*)NetPacket.MsgDevSearch.DevSearchInfo.PTPUUID,   	(char*)FacInfo.PTPUUID);
   			strcpy((char*)NetPacket.MsgDevSearch.DevSearchInfo.PTPCMEI,   	(char*)FacInfo.PTPCMEI);
			strcpy((char*)NetPacket.MsgDevSearch.DevSearchInfo.HardWareVersion,(char*)HVersion);
			strcpy((char*)NetPacket.MsgDevSearch.DevSearchInfo.SoftWareVersion,(char*)SVersion);
			strcpy((char*)NetPacket.MsgDevSearch.DevSearchInfo.sensor,		(char*)FacInfo.sensor);			
			NetPacket.MsgDevSearch.DevSearchInfo.FactoryTime			= FacInfo.FactoryTime;
			NetPacket.MsgDevSearch.DevSearchInfo.LogoType				= FacInfo.LogoType;
			NetPacket.MsgDevSearch.DevSearchInfo.WifiOFF				= FacInfo.WifiOFF;
			NetPacket.MsgDevSearch.DevSearchInfo.SDOFF					= FacInfo.SDOFF;
			NetPacket.MsgDevSearch.DevSearchInfo.AudioInOFF				= FacInfo.AudioInOFF;
			NetPacket.MsgDevSearch.DevSearchInfo.AudioOutOFF			= FacInfo.AudioOutOFF;
			NetPacket.MsgDevSearch.DevSearchInfo.ThreeMachineSupport 	= FacInfo.ThreeMachineSupport;
			NetPacket.MsgDevSearch.DevSearchInfo.IOOFF					= FacInfo.IOOFF;
			NetPacket.MsgDevSearch.DevSearchInfo.nVideoChannel			= 1;
			NetPacket.MsgDevSearch.DevSearchInfo.bIsVideoSubChannel		= 1;
			NetPacket.MsgDevSearch.DevSearchInfo.nAudioChannel			= 1;

			{
				GetDevSysInfo(NetPacket.MsgDevSearch.DevSearchInfo.Uptime, &NetPacket.MsgDevSearch.DevSearchInfo.FreeMem);
			}
			
			timetmp = NetPacket.MsgDevSearch.DevSearchInfo.FactoryTime;
			t = localtime(&timetmp);
			IPCAM_DEBUG("nChannel =%d", FacInfo.nChannel);
			IPCAM_DEBUG("devModel = [%s]", FacInfo.devModel);
			IPCAM_DEBUG("devSerialNumb = [%s]", FacInfo.devSerialNumb);
			IPCAM_DEBUG("devRegcode = %s",	  FacInfo.devRegcode);
			IPCAM_DEBUG("devName = %s",   FacInfo.devName);
			IPCAM_DEBUG("FactoryTime = %02d:%02d:%02d",t->tm_year+1900,t->tm_mon+1,t->tm_mday);
			IPCAM_DEBUG("szFactoryName = %s",   FacInfo.szFactoryName);
			IPCAM_DEBUG("LogoType 	= %d",   FacInfo.LogoType);
			IPCAM_DEBUG("Sensor	= %s",   NetPacket.MsgDevSearch.DevSearchInfo.sensor);
	  		IPCAM_DEBUG("PTPUUID = %s",   FacInfo.PTPUUID);
	  		IPCAM_DEBUG("PTPCMEI = %s",   FacInfo.PTPCMEI);	
			IPCAM_DEBUG("WifiOFF = %d",   FacInfo.WifiOFF);
			IPCAM_DEBUG("SDOFF 	= %d",   FacInfo.SDOFF);
			IPCAM_DEBUG("AudioInOFF = %d",   FacInfo.AudioInOFF);
			IPCAM_DEBUG("AudioOutOFF = %d",   FacInfo.AudioOutOFF);
	  		IPCAM_DEBUG("ThreeMachineSupport = %d",   FacInfo.ThreeMachineSupport);
			IPCAM_DEBUG("IOOFF = %d",   FacInfo.IOOFF);
			IPCAM_DEBUG("HardWareVersion = %s",   NetPacket.MsgDevSearch.DevSearchInfo.HardWareVersion);
			IPCAM_DEBUG("SoftWareVersion = %s",   NetPacket.MsgDevSearch.DevSearchInfo.SoftWareVersion);
			IPCAM_DEBUG("Vendor information space remaining %d bytes before use",sizeof(NetPacket.MsgBuf) - sizeof(NetPacket.MsgDevSearch));
			
			memcpy(&NetPacket.MsgHead.subType, (USHORT*)&DevSelfCode, sizeof(USHORT));
			NetPacket.MsgHead.msgType  = MSG_SEARCHQUERY_RESP;
			#ifdef ETH_NET
			if(SendSocketFd > 0 && NetInfo.NetIpAddr[0] != 0 && NetInfo.NetIpAddr[0] != '0')
				sendto(SendSocketFd, (NETMSGPACKET *)&NetPacket, sizeof(NETMSGPACKET), SIZEOFNETMSGPACK,(struct sockaddr*) &SendAddr, AddrLen);
			#endif
			if(Ra0SendSocketFd > 0)
			{	
				strcpy((char*)NetPacket.MsgDevSearch.DevSearchInfo.NetIpAddr, ra0IpAddr);
				pox_get_gateway(NET_WLAN,(char*)NetPacket.MsgDevSearch.DevSearchInfo.NetGwAddr);
				pox_get_netmask(NET_WLAN, (char*)NetPacket.MsgDevSearch.DevSearchInfo.NetSubMask);
				pox_get_macaddr(NET_WLAN, (char*)NetPacket.MsgDevSearch.DevSearchInfo.NetMacAddr);
				IPCAM_DEBUG("IP %s gw %s mask %s mac %s", NetPacket.MsgDevSearch.DevSearchInfo.NetIpAddr, NetPacket.MsgDevSearch.DevSearchInfo.NetGwAddr, 
					NetPacket.MsgDevSearch.DevSearchInfo.NetSubMask, NetPacket.MsgDevSearch.DevSearchInfo.NetMacAddr);
				IPCAM_DEBUG("DnsI %s DnsII %s", NetPacket.MsgDevSearch.DevSearchInfo.NetDnsSvI, NetPacket.MsgDevSearch.DevSearchInfo.NetDnsSvII);

				if(ra0IpAddr[0] != 0 && ra0IpAddr[0] != '0')
					sendto(Ra0SendSocketFd, (NETMSGPACKET *)&NetPacket, sizeof(NETMSGPACKET), SIZEOFNETMSGPACK,(struct sockaddr*) &SendAddr, AddrLen);
			}
		}
		else if( NetPacket.MsgHead.msgType == MSG_NETPARMSET_REQ &&  0 == memcmp(&NetPacket.MsgHead.subType, (USHORT*)&DevSelfCode, sizeof(USHORT)))
		{    

			
			NetPacket.MsgHead.msgType  = MSG_NETPARMSET_RESP;
			//mod 20161220 
			#ifdef ETH_NET
			if(SendSocketFd > 0)
				sendto(SendSocketFd, (NETMSGPACKET *)&NetPacket, sizeof(NETMSGPACKET), SIZEOFNETMSGPACK,(struct sockaddr*) &SendAddr, AddrLen);            
			#endif
			if(Ra0SendSocketFd > 0)
                sendto(Ra0SendSocketFd, (NETMSGPACKET *)&NetPacket, sizeof(NETMSGPACKET), SIZEOFNETMSGPACK,(struct sockaddr*) &SendAddr, AddrLen);            
			
			if(NETPARAM_IP_MODE == NetPacket.MsgDevSearch.DevSearchInfo.ipFetchMode)
			{
				if(0 != CheckGetWay( NetPacket.MsgDevSearch.DevSearchInfo.NetIpAddr,
			    					 NetPacket.MsgDevSearch.DevSearchInfo.NetSubMask,
			 						 NetPacket.MsgDevSearch.DevSearchInfo.NetGwAddr))
			 	{
					NetPacket.MsgHead.errCode  = FALSE;
					if(SendSocketFd > 0)
						sendto(SendSocketFd, (NETMSGPACKET *)&NetPacket, sizeof(NETMSGPACKET), SIZEOFNETMSGPACK,(struct sockaddr*) &SendAddr, AddrLen);
					continue;
				}
				
				memset(Cmd, 0, sizeof(Cmd));
				sprintf(Cmd, "ifconfig eth0 %s netmask %s up",NetPacket.MsgDevSearch.DevSearchInfo.NetIpAddr,
				NetPacket.MsgDevSearch.DevSearchInfo.NetSubMask);
				hi_system(Cmd);

				memset(Cmd, 0, sizeof(Cmd));
				strcpy(Cmd,"route del default ");
				hi_system(Cmd);
				memset(Cmd, 0, sizeof(Cmd));
				sprintf(Cmd, "route add default gw %s",NetPacket.MsgDevSearch.DevSearchInfo.NetGwAddr);
				hi_system(Cmd); 

				LOGE("ipaddr=%s mask=%s gw=%s\n",
				       NetPacket.MsgDevSearch.DevSearchInfo.NetIpAddr,
				       NetPacket.MsgDevSearch.DevSearchInfo.NetSubMask,
				       NetPacket.MsgDevSearch.DevSearchInfo.NetGwAddr);
				SaveEthAttr2File(TYPE_IP, (char *)NetPacket.MsgDevSearch.DevSearchInfo.NetIpAddr);
				SaveEthAttr2File(TYPE_NETMASK, (char *)NetPacket.MsgDevSearch.DevSearchInfo.NetSubMask);
				SaveEthAttr2File(TYPE_GATEWAY, (char *)NetPacket.MsgDevSearch.DevSearchInfo.NetGwAddr);
			}
			else if(NETPARAM_DHCP_MODE == NetPacket.MsgDevSearch.DevSearchInfo.ipFetchMode)
			{
				hi_system("udhcpc -n -q -i eth0");
			}
		}
		else if( NetPacket.MsgHead.msgType == MSG_FACTORYINFOSET_REQ &&  0 == memcmp(&NetPacket.MsgHead.subType, (USHORT*)&DevSelfCode, sizeof(USHORT)))
		{	
			//read facinfo,save PTPDevKey,memset other 0
			memset(&FacInfo, 0, sizeof(FacInfo));
			IPCAM_ReadFacInfo((VOID*)&FacInfo);
			memset(&FacInfo, 0, sizeof(FacInfo) - sizeof(FacInfo.PTPDevKey));
			IPCAM_DEBUG("PTPDevKey = %s", FacInfo.PTPDevKey);
			
			char *pTemp = NULL;
			pTemp = strrchr((char*)NetPacket.MsgDevSearch.DevSearchInfo.devSerialNumb, '-');
			if (NULL != pTemp){
				pTemp += 12;
				sscanf(pTemp, "%x", &FacInfo.devNo);
			}else{
				FacInfo.devNo = DEV_NO;
			}
			IPCAM_DEBUG("devNo = %x", FacInfo.devNo);

			strcpy((char*)FacInfo.devModel, 		(char*)NetPacket.MsgDevSearch.DevSearchInfo.devModel);
			strcpy((char*)FacInfo.devSerialNumb, 	(char*)NetPacket.MsgDevSearch.DevSearchInfo.devSerialNumb);
			strcpy((char*)FacInfo.devRegcode, 		(char*)NetPacket.MsgDevSearch.DevSearchInfo.devRegcode);
			strcpy((char*)FacInfo.devName, 			(char*)NetPacket.MsgDevSearch.DevSearchInfo.devName);
			strcpy((char*)FacInfo.szFactoryName, 	(char*)NetPacket.MsgDevSearch.DevSearchInfo.szFactoryName);
			strcpy((char*)FacInfo.PTPUUID, 			(char*)NetPacket.MsgDevSearch.DevSearchInfo.PTPUUID);
			if(strlen(NetPacket.MsgDevSearch.DevSearchInfo.PTPCMEI) > 15){
				strncpy((char*)FacInfo.PTPCMEI, 	(char*)NetPacket.MsgDevSearch.DevSearchInfo.PTPCMEI, 15);
			}else{
				strcpy((char*)FacInfo.PTPCMEI, 		(char*)NetPacket.MsgDevSearch.DevSearchInfo.PTPCMEI);
			}
				
			strcpy((char*)FacInfo.sensor,			(char*)NetPacket.MsgDevSearch.DevSearchInfo.sensor);
			FacInfo.FactoryTime 		= NetPacket.MsgDevSearch.DevSearchInfo.FactoryTime;
			FacInfo.LogoType    		= NetPacket.MsgDevSearch.DevSearchInfo.LogoType;
			FacInfo.WifiOFF				= NetPacket.MsgDevSearch.DevSearchInfo.WifiOFF;
			FacInfo.SDOFF				= NetPacket.MsgDevSearch.DevSearchInfo.SDOFF;
			FacInfo.AudioInOFF			= NetPacket.MsgDevSearch.DevSearchInfo.AudioInOFF;
			FacInfo.AudioOutOFF			= NetPacket.MsgDevSearch.DevSearchInfo.AudioOutOFF;
			FacInfo.ThreeMachineSupport = NetPacket.MsgDevSearch.DevSearchInfo.ThreeMachineSupport;
			FacInfo.IOOFF				= NetPacket.MsgDevSearch.DevSearchInfo.IOOFF;
			FacInfo.nChannel            = NetPacket.MsgDevSearch.DevSearchInfo.nVideoChannel;
			
			timetmp = FacInfo.FactoryTime;
			t = localtime(&timetmp);
			if(NULL == strrchr((char*)FacInfo.devSerialNumb, '-')){
				char macAddr[24];
							
				if( 1 == ProductGetHandle()->bLAN )
				{
					pox_get_macaddr(NET_ETH,macAddr);
				}
			    else 
			    {
					pox_get_macaddr(NET_WLAN,macAddr);
				}

				sprintf((char*)FacInfo.devSerialNumb, "RL01-RL0808-%c%c%c%c%c%c%c%c%c%c%c%c123456", 
					macAddr[0], macAddr[1], macAddr[3], macAddr[4], macAddr[6], macAddr[7], macAddr[9], macAddr[10], 
					macAddr[12], macAddr[13], macAddr[15], macAddr[16]);
			}
			IPCAM_DEBUG("nChannel = %d", FacInfo.nChannel);
			IPCAM_DEBUG("devModel = [%s]", FacInfo.devModel);
			IPCAM_DEBUG("devSerialNumb = [%s]", FacInfo.devSerialNumb);
			IPCAM_DEBUG("devRegcode = %s",	  FacInfo.devRegcode);
			IPCAM_DEBUG("devName = %s",   FacInfo.devName);
			IPCAM_DEBUG("FactoryTime = %02d:%02d:%02d",t->tm_year+1900,t->tm_mon+1,t->tm_mday);
			IPCAM_DEBUG("szFactoryName = %s",   FacInfo.szFactoryName);
			IPCAM_DEBUG("LogoType 	= %d",   FacInfo.LogoType);
			IPCAM_DEBUG("Sensor	= %s",   NetPacket.MsgDevSearch.DevSearchInfo.sensor);
	  		IPCAM_DEBUG("PTPUUID = %s",   FacInfo.PTPUUID);
	  		IPCAM_DEBUG("PTPCMEI = %s",   FacInfo.PTPCMEI);		
			IPCAM_DEBUG("WifiOFF = %d",   FacInfo.WifiOFF);
			IPCAM_DEBUG("SDOFF 	= %d",   FacInfo.SDOFF);
			IPCAM_DEBUG("AudioInOFF = %d",   FacInfo.AudioInOFF);
			IPCAM_DEBUG("AudioOutOFF = %d",   FacInfo.AudioOutOFF);
	  		IPCAM_DEBUG("ThreeMachineSupport = %d",   FacInfo.ThreeMachineSupport);
			IPCAM_DEBUG("IOOFF = %d",   FacInfo.IOOFF);
			IPCAM_DEBUG("HardWareVersion = %s",   NetPacket.MsgDevSearch.DevSearchInfo.HardWareVersion);
			IPCAM_DEBUG("Vendor information space remaining %d bytes before use",sizeof(NetPacket.MsgBuf) - sizeof(NetPacket.MsgDevSearch));


			if(CheckUuid(&FacInfo) < 0 )  

			{
				LOGE("UUID or CMEI is error\n ");
			}
			else
			{
				IPCAM_WriteFacInfo((VOID*)&FacInfo); //保存信息到 factory flash
				unlink("/app/ipcam/ipcam.conf");

				IPCAM_DEBUG("ipFetchMode = %d", NetPacket.MsgDevSearch.DevSearchInfo.ipFetchMode);
				NetPacket.MsgHead.msgType = MSG_FACTORYINFOSET_RESP;
				//mod 20161220 
				#ifdef ETH_NET
				if(SendSocketFd > 0)
					sendto(SendSocketFd, (NETMSGPACKET *)&NetPacket, sizeof(NETMSGPACKET), SIZEOFNETMSGPACK,(struct sockaddr*) &SendAddr, AddrLen);
				#endif
				if(Ra0SendSocketFd > 0)
					sendto(Ra0SendSocketFd, (NETMSGPACKET *)&NetPacket, sizeof(NETMSGPACKET), SIZEOFNETMSGPACK,(struct sockaddr*) &SendAddr, AddrLen);

				if( 1 == ProductGetHandle()->bLAN )
				{
					Daemon_ChangeMacAddr(&FacInfo,NET_ETH,1);
				}
				else 
				{
					Daemon_ChangeMacAddr(&FacInfo,NET_WLAN,1);
				}
			}

		}else if( NetPacket.MsgHead.msgType == MSG_DEVREGIST_REQ &&  0 == memcmp(&NetPacket.MsgHead.subType, (USHORT*)&DevSelfCode, sizeof(USHORT)))  {
			IPCAM_DEBUG("MSG_DEVREGIST_REQ");
			//按类型操作: 设备注册make
			NetPacket.MsgHead.msgType  = MSG_DEVREGIST_RESP;
			if(SendSocketFd > 0)
				sendto(SendSocketFd, (NETMSGPACKET *)&NetPacket, sizeof(NETMSGPACKET), SIZEOFNETMSGPACK,(struct sockaddr*) &SendAddr, AddrLen);               
			perror("sendto");
		}else if (MSG_DEVKEYSET_REQ == NetPacket.MsgHead.msgType && 0 == memcmp(&NetPacket.MsgHead.subType, (USHORT*)&DevSelfCode, sizeof(USHORT))){
			IPCAM_DEBUG("MSG_DEVKEYSET_REQ");
			//read and write Facinfo .....
			memset(&FacInfo, 0, sizeof(FacInfo));
			IPCAM_ReadFacInfo((VOID*)&FacInfo);
			memset(FacInfo.PTPDevKey, 0, sizeof(FacInfo.PTPDevKey));
			if(strlen(NetPacket.MsgDevKey.DeviceKey.DeviceKey) > 72){
				strncpy((char*)FacInfo.PTPDevKey, (char*)NetPacket.MsgDevKey.DeviceKey.DeviceKey, 72);
			}else{
				strcpy((char*)FacInfo.PTPDevKey, (char*)NetPacket.MsgDevKey.DeviceKey.DeviceKey);
			}
				
			
			IPCAM_DEBUG("set devkey=%s\n", NetPacket.MsgDevKey.DeviceKey.DeviceKey);
			IPCAM_WriteFacInfo((VOID*)&FacInfo);
			
			NetPacket.MsgHead.msgType  = MSG_DEVKEYSET_RESP;
			#ifdef ETH_NET
			if(SendSocketFd > 0)
				sendto(SendSocketFd, (NETMSGPACKET *)&NetPacket, sizeof(NETMSGPACKET), SIZEOFNETMSGPACK,(struct sockaddr*) &SendAddr, AddrLen);               
			#endif
			if(Ra0SendSocketFd > 0)
				sendto(Ra0SendSocketFd, (NETMSGPACKET *)&NetPacket, sizeof(NETMSGPACKET), SIZEOFNETMSGPACK,(struct sockaddr*) &SendAddr, AddrLen);
			perror("sendto");
		}else if (MSG_DEVKEYQUERY_REQ == NetPacket.MsgHead.msgType && 0 == memcmp(&NetPacket.MsgHead.subType, (USHORT*)&DevSelfCode, sizeof(USHORT))){
			IPCAM_DEBUG("MSG_DEVKEYQUERY_REQ");
			//read FacInfo .....
			memset(&FacInfo, 0, sizeof(FacInfo));
			IPCAM_ReadFacInfo((VOID*)&FacInfo);
   			strcpy((char*)NetPacket.MsgDevKey.DeviceKey.DeviceKey, (char*)FacInfo.PTPDevKey);
			IPCAM_DEBUG("get devkey=%s\n", NetPacket.MsgDevKey.DeviceKey.DeviceKey);

			NetPacket.MsgHead.msgType  = MSG_DEVKEYQUERY_RESP;
			#ifdef ETH_NET
			if(SendSocketFd > 0)
				sendto(SendSocketFd, (NETMSGPACKET *)&NetPacket, sizeof(NETMSGPACKET), SIZEOFNETMSGPACK,(struct sockaddr*) &SendAddr, AddrLen);               
			#endif
			if(Ra0SendSocketFd > 0)
				sendto(Ra0SendSocketFd, (NETMSGPACKET *)&NetPacket, sizeof(NETMSGPACKET), SIZEOFNETMSGPACK,(struct sockaddr*) &SendAddr, AddrLen);

			perror("sendto");
		}else if (MSG_LOADCFG_REQ == NetPacket.MsgHead.msgType && 0 == memcmp(&NetPacket.MsgHead.subType, (USHORT*)&DevSelfCode, sizeof(USHORT))){
			unlink("/app/ipcam/ipcam.log");
			unlink("/app/ipcam/ipcam.conf");
			NetPacket.MsgHead.msgType  = MSG_LOADCFG_RESP;
			if(SendSocketFd > 0)
				sendto(SendSocketFd, (NETMSGPACKET *)&NetPacket, sizeof(NETMSGPACKET), SIZEOFNETMSGPACK,(struct sockaddr*) &SendAddr, AddrLen);               
			perror("sendto");
			sync();
			hi_system("reboot");
			sleep(5);
			hi_system("reboot -f");//wzj: if reboot failed,use reboot -f to reboot
		}else if (MSG_REBOOT_REQ == NetPacket.MsgHead.msgType && 0 == memcmp(&NetPacket.MsgHead.subType, (USHORT*)&DevSelfCode, sizeof(USHORT))){
			IPCAM_DEBUG("MSG_REBOOT_REQ");
			NetPacket.MsgHead.msgType  = MSG_REBOOT_RESP;
			if(SendSocketFd > 0)
				sendto(SendSocketFd, (NETMSGPACKET *)&NetPacket, sizeof(NETMSGPACKET), SIZEOFNETMSGPACK,(struct sockaddr*) &SendAddr, AddrLen); 			  
			perror("sendto");
			
			memset(Cmd,0,128);
			sprintf(Cmd,"killall %s",PROGRAM_IPCAM);
			
			hi_system(Cmd);
			sleep(3);
			sync();
			hi_system("reboot");
			sleep(5);
			hi_system("reboot -f");//wzj: if reboot failed,use reboot -f to reboot
		}
		else if(MSG_AGING_REQ == NetPacket.MsgHead.msgType  && 0 == memcmp(&NetPacket.MsgHead.subType, (USHORT*)&DevSelfCode, sizeof(USHORT)))
		{
			IPCAM_DEBUG("MSG_AGING_REQ");
			IPCAM_CREATE_THREADEX(Func_age,NULL,iRet);
			NetPacket.MsgHead.msgType = MSG_AGING_RESP;
			if(SendSocketFd > 0)
				sendto(SendSocketFd, (NETMSGPACKET *)&NetPacket, sizeof(NETMSGPACKET), SIZEOFNETMSGPACK,(struct sockaddr*) &SendAddr, AddrLen);
			perror("send to");
		}
		else if( MSG_DEVICEOPER_CMD_REQ == NetPacket.MsgHead.msgType && 0 == memcmp(&NetPacket.MsgHead.subType, (USHORT*)&DevSelfCode, sizeof(USHORT)))
		{
			Daemon_GetMacAddr(pMacAddr);
			if ( 0 != strcasecmp((char*)NetPacket.MsgDevCmd.DevMacAddr, pMacAddr))
			{
				#define MAXCHARLENTH   sizeof(NetPacket.MsgDevCmd.cmd)
				IPCAM_DEBUG("--------Device CMD Operation-------");
				if(strlen(NetPacket.MsgDevCmd.cmd) == 0 || strlen(NetPacket.MsgDevCmd.cmd) > MAXCHARLENTH)
				{
					NetPacket.MsgHead.errCode = 0;
					IPCAM_DEBUG("Current command is empty or command length of overflow,please check your command");
				}
				else
				{
					IPCAM_DEBUG("command: %s",NetPacket.MsgDevCmd.cmd);
					hi_system(NetPacket.MsgDevCmd.cmd);
					NetPacket.MsgHead.errCode= 1;
				}
				NetPacket.MsgHead.msgType = MSG_DEVICEOPER_CMD_RESP;
				if(SendSocketFd > 0)
					sendto(SendSocketFd, (NETMSGPACKET *)&NetPacket, sizeof(NETMSGPACKET), SIZEOFNETMSGPACK,(struct sockaddr*) &SendAddr, AddrLen);
			}
		}
		else
		{
			IPCAM_DEBUG("Recv a Unkown Packet [%x]", NetPacket.MsgHead.msgType);
		}
	}
	if( SendSocketFd >= 0 )
	{
		shutdown(SendSocketFd, SHUT_RDWR);
		close(SendSocketFd);
		shutdown(RecvSocketFd, SHUT_RDWR);
		close(RecvSocketFd);
	}
	free(pMacAddr);
	IPCAM_DEBUG("PTH_NetDevFound Exit");
	pthread_exit(NULL);
}

BOOL Daemon_StartNetBroadCastFound(LPTHREAD_ARG* arg)
{
	INT Ret = 0;
    SAVENANDINFO_T t_FacInfo;
	
    Ret = IPCAM_ReadFacInfo(&t_FacInfo);
    if (Ret == FALSE)
    {
        IPCAM_WriteFacInfo(&t_FacInfo);
    }


	if( 1 == ProductGetHandle()->bLAN ) 
	{
		Daemon_ChangeMacAddr(&t_FacInfo, NET_ETH,0);   //整理mac addr       
	}    
	
	IPCAM_CREATE_THREADEX(Pthread_NetDevBroadCastFound, arg, Ret);

	IPCAM_CREATE_THREADEX(Pthread_NetDevBroadCastFound1, arg, Ret);
	return Ret;
}

